<template>
  <el-dialog :model-value="modelValue" title="选择物品" width="880px" @close="onClose">
    <div class="filters">
      <el-input v-model="kw" placeholder="请输入物品编号/名称/规格型号" clearable style="width: 260px;" />
      <el-select v-model="cat" placeholder="请选择物品类别" clearable style="width: 180px;">
        <el-option label="原材料" value="原材料" />
        <el-option label="半成品" value="半成品" />
        <el-option label="成品" value="成品" />
      </el-select>
      <el-select v-model="subcat" placeholder="请选择物品分类" clearable style="width: 180px;">
        <el-option label="金属" value="金属" />
        <el-option label="塑料" value="塑料" />
        <el-option label="木材" value="木材" />
      </el-select>
      <el-select v-model="stockState" placeholder="库存状态" clearable style="width: 140px;">
        <el-option label="有货" value="有货" />
        <el-option label="缺货" value="缺货" />
      </el-select>
      <el-button type="primary" @click="onQuery">查询</el-button>
      <el-button @click="onReset">重置</el-button>
    </div>

    <el-table :data="paged" border stripe height="420" @selection-change="onSelChange" :loading="loading">
      <el-table-column type="selection" width="48" />
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="code" label="物品编号" width="140" />
      <el-table-column prop="name" label="物品名称" min-width="160" />
      <el-table-column prop="spec" label="规格型号" min-width="160" />
      <el-table-column prop="unit" label="单位" width="80" />
      <el-table-column prop="cat" label="物品类别" width="100" />
      <el-table-column prop="subcat" label="物品分类" width="100" />
      <el-table-column prop="brand" label="品牌" width="120" />
      <el-table-column label="总库存" width="120">
        <template #default="{ row }">
          <el-popover placement="right-start" trigger="hover" :width="220" popper-class="stock-popper">
            <template #reference>
              <span class="stock-ref">{{ fmtNum(row.totalStock, 0) }} <span class="caret">▾</span></span>
            </template>
            <div class="stock-popover">
              <div class="title">库存详情：</div>
              <template v-if="row.stockDetails && row.stockDetails.length">
                <div class="line" v-for="d in row.stockDetails" :key="d.name">
                  <span class="name">{{ d.name }}：</span>
                  <span class="qty">{{ fmtNum(d.qty, 0) }}</span>
                </div>
              </template>
              <template v-else>
                <div class="empty">暂无明细</div>
              </template>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="purchasePrice" label="采购单价" width="120" />
      <el-table-column prop="salePrice" label="销售单价" width="120" />
      <template #empty>
        <div class="empty">暂无数据</div>
      </template>
    </el-table>

    <div class="pager">
      <div>共 {{ total }} 项数据</div>
      <div class="right">
        <el-select v-model="pageSize" style="width: 100px; margin-right: 8px;">
          <el-option :value="5" label="5条/页" />
          <el-option :value="10" label="10条/页" />
          <el-option :value="20" label="20条/页" />
        </el-select>
        <el-pagination background layout="prev, pager, next" :total="total" :page-size="pageSize" v-model:current-page="currentPage" />
      </div>
    </div>

    <template #footer>
      <el-button @click="onClose">取消</el-button>
      <el-button type="primary" :disabled="!selected.length" @click="onConfirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, ref, watch, onMounted } from 'vue'
import ERP from '@/utils/Interceptors'

const props = defineProps<{ modelValue: boolean }>()
const emit = defineEmits<{ (e: 'update:modelValue', v: boolean): void; (e: 'confirm', rows: any[]): void }>()

const kw = ref('')
const cat = ref<string | undefined>()
const subcat = ref<string | undefined>()
const stockState = ref<string | undefined>()

const currentPage = ref(1)
const pageSize = ref(5)
const selected = ref<any[]>([])

const loading = ref(false)
const table = ref<any[]>([])
const total = ref(0)

const paged = computed(() => table.value)

async function loadData() {
  loading.value = true
  try {
    const { data } = await ERP.get('/api/items', {
      params: {
        kw: kw.value || undefined,
        cat: cat.value || undefined,
        subcat: subcat.value || undefined,
        stockState: stockState.value || undefined,
        page: currentPage.value,
        pageSize: pageSize.value,
      }
    })
    table.value = data?.items || []
    total.value = data?.total || 0
  } finally {
    loading.value = false
  }
}

function onSelChange(rows: any[]) { selected.value = rows }
function onQuery() { currentPage.value = 1; loadData() }
function onReset() {
  kw.value = ''
  cat.value = undefined
  subcat.value = undefined
  stockState.value = undefined
  currentPage.value = 1
  loadData()
}

function onClose() { emit('update:modelValue', false) }
function onConfirm() { emit('confirm', selected.value); onClose() }

watch(() => props.modelValue, (v) => { if (!v) selected.value = []; if (v) loadData() })
watch([currentPage, pageSize], () => loadData())

function fmtNum(v: any, max: number = 2) {
  if (v === null || v === undefined || v === '') return ''
  const n = Number(v)
  if (Number.isNaN(n)) return String(v)
  let s = n.toString().replace(/(\.\d*?)0+$/, '$1').replace(/\.$/, '')
  if (s.includes('.')) {
    const [, frac = ''] = s.split('.')
    if (frac.length > max) {
      s = n.toFixed(max).replace(/(\.\d*?)0+$/, '$1').replace(/\.$/, '')
    }
  }
  return s
}
</script>

<style scoped>
.filters { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; flex-wrap: wrap; }
.pager { display: flex; align-items: center; justify-content: space-between; margin-top: 8px; }
.empty { padding: 24px; text-align: center; color: #999; }
.stock-ref { cursor: default; user-select: none; }
.stock-popover { background: #fff; padding: 8px 12px; border-radius: 6px; box-shadow: 0 6px 18px rgba(0,0,0,0.12); }
.stock-popover .title { font-weight: 600; color: #333; margin-bottom: 6px; }
.stock-popover .line { display: flex; align-items: center; justify-content: space-between; line-height: 22px; }
.stock-popover .name { color: #555; margin-right: 8px; }
.stock-popover .qty { color: #111; min-width: 40px; text-align: right; }
.caret { color: #999; margin-left: 4px; }
</style>
